<template>
  <div class="purchase_failed">
    <!-- 头部 -->
    <CommonHeader :balance="gemsNum" />
    <div class="suceess_content">
      <div class="text">Sorry! Purchase failed</div>
      <div class="text">A small error has occurred.<br />Please try again</div>
      <van-button type="primary" class="btn_top" @click="goViewMyCreation">Retry</van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import CommonHeader from "@/components/CommonHeader.vue";
import api from "@/api";
import { trackEvent } from '@/utils/firebase';
const router = useRouter();
const gemsNum = ref("");
const isPay = ref(false);
const goViewMyCreation = () => {
  router.push("/myDiamonds");
}

// 查询积分余额
const queryBalance = async () => {
  try {
    const res = await api.pointsBalance();
    gemsNum.value = String(res.data.balance);
  } catch (err) {
    console.log(err);
  }
};

const getUseInfo = async () => {
  try {
    const response = await api.userInfo();
    if (response.data.rechargeStatus === 1) {
      isPay.value = true;
    } else {
      isPay.value = false;
    }
  } catch (err) {
    console.log(err);
  }
};

onMounted(async () => {
  queryBalance();
  await getUseInfo();
  // 读取并校验 24h 过期的 keepback 标记
  let alreadyShownValid = false;
  try {
    const raw = localStorage.getItem('havedShowKeepBack');
    if (raw) {
      const data = JSON.parse(raw);
      if (data && data.expiry && Date.now() < Number(data.expiry)) {
        alreadyShownValid = true;
      } else {
        localStorage.removeItem('havedShowKeepBack');
      }
    }
  } catch {
    localStorage.removeItem('havedShowKeepBack');
  }

  if (!isPay.value && !alreadyShownValid) {
    router.push('/keepBack');
    return;
  }
  trackEvent('支付失败', { type: 'GooglePay', error_code: '' });
});
</script>

<style lang="less" scoped>
.purchase_failed {
  .suceess_content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding-top: 140px;

    .diamond_72_img {
      width: 72px;
    }

    .text {
      margin-top: 15px;
      text-align: center;
    }

    .btn_top {
      margin-top: 20px;
    }

    .btn_bottom {
      margin-top: 20px;
    }
  }
}
</style>
